package com.example.play.vm

import androidx.lifecycle.viewModelScope
import com.example.common.vm.BaseViewModel
import com.example.play.intent.PlayViewIntent
import com.example.play.model.PlayRepository
import com.example.play.state.PlayUiState

import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

import javax.inject.Inject

@HiltViewModel
class PlayViewModel @Inject constructor(private val repository:PlayRepository):BaseViewModel<PlayViewIntent>(){

    private val _uiState = MutableSharedFlow<PlayUiState>()
    val uiState:SharedFlow<PlayUiState> = _uiState.asSharedFlow()


    override fun dispatchIntent(intent: PlayViewIntent) {
        when(intent){
            is PlayViewIntent.LoadSimpleVideoListById -> loadSimpleViewById(intent.channelId,intent.page,intent.pageSize)
            is PlayViewIntent.LoadRecommendSimpleVideoList -> loadRecommendSimpleVideo(intent.page,intent.pageSize)
        }
    }

    private fun loadSimpleViewById(channelId:String,page:Int,pageSize:Int){
        viewModelScope.launch(Dispatchers.IO){
            try {
                withContext(Dispatchers.Main){
                    repository.getSimpleVideoByChannelId(channelId,page,pageSize).collect{
                        if(it.isNotEmpty()){
                            _uiState.emit(PlayUiState.LoadSimpleVideoSuccess(it))
                        }else{
                            _uiState.emit(PlayUiState.LoadSimpleVideoFail("没有此视频"))
                        }
                    }
                }
            }catch (e:Exception){
                e.printStackTrace()
                _uiState.emit(PlayUiState.LoadSimpleVideoFail("请求异常"+e.message))
            }finally {
                cancel()
            }
        }
    }
    private fun loadRecommendSimpleVideo(page:Int,pageSize: Int){

        viewModelScope.launch(Dispatchers.IO){
            try {
                withContext(Dispatchers.Main){
                    repository.getRecommendVideo(page,pageSize).collect{
                        if(it.isNotEmpty()){
                            _uiState.emit(PlayUiState.LoadSimpleVideoSuccess(it))
                        }else{
                            _uiState.emit(PlayUiState.LoadSimpleVideoFail("没有此类视频"))
                        }
                    }
                }
            }catch (e:Exception){
                e.printStackTrace()
                _uiState.emit(PlayUiState.LoadSimpleVideoFail("请求异常"+e.message))
            }finally {
                cancel()
            }
        }
    }



}